import React, { useState, useEffect } from "react";
import { Box, TextField, Paper } from "@mui/material";
import Message from "./Message";
import Image from "next/image";

type MessageType = {
  role: "user" | "assistant";
  content: string;
};

// ChatBox 组件，用于处理聊天逻辑和界面
const ChatBox: React.FC = () => {
  const [messages, setMessages] = useState<MessageType[]>([]); // 存储列表
  const [input, setInput] = useState<string>(""); // 输入内容
  const [apiKey, setApiKey] = useState<string>(""); // API 密钥的状态
  const [isLoading, setIsLoading] = useState<boolean>(false); // 是否正在加载

  // 发送消息的处理函数
  const handleSend = async () => {
    if (!input) return;
    setIsLoading(true);
    const userMessage: MessageType = { role: "user", content: input };
    const chatMessage: MessageType = { role: "assistant", content: "..." };
    const newMessage = [...messages, userMessage, chatMessage];
    setMessages(newMessage);
    setInput("");

    try {
      const response: any = await fetch(
        "https://openrouter.ai/api/v1/chat/completions",
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${apiKey}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            model: "mistralai/mistral-7b-instruct:free",
            messages: [...messages, userMessage],
          }),
        }
      );
      const res = await response.json();
      const aiMessage: MessageType = {
        role: "assistant",
        content: res.choices[0].message.content,
      };
      setMessages((prevMessages) => {
        const newMsgs = prevMessages.slice(0, -1);
        return [...newMsgs, aiMessage];
      });
      setIsLoading(false);
    } catch (error) {
      console.error("Error fetching AI response:", error);
    }
  };

  // 初次加载时提示用户输入 API 密钥
  useEffect(() => {
    if (!apiKey) {
      setApiKey(window.prompt("请输入你的 API 密钥") || "");
    }
  }, []);

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        p: 2,
        width: "100%",
      }}
    >
      <Paper
        sx={{
          width: "100%",
          maxWidth: 1080,
          mb: 2,
          p: 2,
          height: "85vh",
          overflowY: "auto",
          boxShadow: "none",
        }}
      >
        {messages.map((msg, index) => (
          <Message key={index} sender={msg.role} text={msg.content} />
        ))}
      </Paper>
      <Box sx={{ display: "flex", width: "100%", position: "relative" }}>
        <TextField
          fullWidth
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Message ChatGPT.."
          onKeyDown={(e) => {
            if (e.key === "Enter") handleSend();
          }}
        />
        {input && !isLoading && (
          <Image
            src="/bg-up-activa.png"
            alt="发送"
            width={36}
            height={36}
            onClick={handleSend}
            style={{
              position: "absolute",
              right: "20px",
              top: "50%",
              transform: "translateY(-50%)",
              cursor: "pointer",
            }}
          />
        )}
        {!input && !isLoading && (
          <Image
            src="/bg-up.png"
            alt="发送"
            width={36}
            height={36}
            style={{
              position: "absolute",
              right: "20px",
              top: "50%",
              transform: "translateY(-50%)",
              cursor: "pointer",
            }}
          />
        )}
        {isLoading && (
          <Image
            src="/stop.png"
            alt="发送"
            width={36}
            height={36}
            style={{
              position: "absolute",
              right: "20px",
              top: "50%",
              transform: "translateY(-50%)",
              cursor: "pointer",
            }}
          />
        )}
      </Box>
    </Box>
  );
};

export default ChatBox;
